package com.xyzk.diagnose.view.dialog;
import com.xyzk.diagnose.R;
import com.xyzk.diagnose.tools.Common;
import com.xyzk.diagnose.tools.Commonfunc;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class ShowDialog extends  BaseDialog  implements android.view.View.OnClickListener{
	private Context context;
	private Button btnSure, btnCancel;
	private TextView tvContent;
	private int time = 0;
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case Common.DIALOG_SHOW_TEXT:
					btnSure.setText(msg.arg1 + " S");
					break;
				case Common.DIALOG_WAIT_AUTO_CLOSE:
					Common.dialogResult = true;
					Common.wait = false;
					dismiss();
					break;
			}
		};
	};

	public ShowDialog(Activity context) {
		super(context, R.id.tv_dialog_show);
		this.context = context;
		initViews();
	}

	/**
	 * 初始化控件
	 * @param view
	 */
	private void initViews(){
		tvContent = (TextView) super.initView();
		btnSure = super.getButtonSure();
		btnCancel = super.getButtonCancel();
		btnSure.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_dialog_sure:
				setAutoClose();
				break;
			case R.id.btn_dialog_cancel:
				Common.dialogResult = false;
				Common.wait = false;
				dismiss();
				break;
		}
	}

	/**
	 * 等待并自动关闭
	 */
	public void setAutoClose(){
		btnSure.setClickable(false);//禁用按钮
		new Thread(){
			@Override
			public void run() {
				for(int i = time; i > 0; i--){
					if(!Common.wait) break;
					handler.obtainMessage(Common.DIALOG_SHOW_TEXT, i, 0).sendToTarget();
					Commonfunc.sleep(1000);
				}
				handler.obtainMessage(Common.DIALOG_WAIT_AUTO_CLOSE, 0, 0).sendToTarget();
			}
		}.start();
	}

	/**
	 * 设置时间
	 * @param time
	 */
	public void setTime(int time){
		this.time = time;
	}

	/**
	 * 设置显示内容
	 * @param text
	 */
	public void setText(String text){
		tvContent.setText(text);
	}

	/**
	 * 设置显示内容
	 * @param resId 资源Id
	 */
	public void setText(int resId){
		tvContent.setText(context.getString(resId));
	}
}
